/**
 * Created in 2012-3-1.
 */
package com.surekam.mnai.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.surekam.mnai.entity.LoadPattern;
import com.surekam.mnai.model.Address;
import com.surekam.mnai.model.MobileNumberAttribution;
import com.surekam.mnai.service.IAddressService;
import com.surekam.mnai.service.IMobileNumAttributionService;
import com.surekam.mnai.util.LoggerUtil;
import com.surekam.mnai.web.Pagination;

/**
 * 手机号码信息管理服务类。
 * 
 * @author 吴政
 * 
 */
public class MobileNumberManageServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static Logger log = LoggerFactory
			.getLogger(MobileNumberManageServlet.class);

	static List<MobileNumberAttribution> list = createList();

	private static List<MobileNumberAttribution> createList() {
		List<MobileNumberAttribution> list = new ArrayList<MobileNumberAttribution>();
		list.add(new MobileNumberAttribution(String.valueOf(System
				.currentTimeMillis()), "test", Address.UNKNOW, new Date()));
		list.add(new MobileNumberAttribution("2222222", "test", Address.UNKNOW,
				new Date()));
		list.add(new MobileNumberAttribution("3333333", "test", Address.UNKNOW,
				new Date()));
		list.add(new MobileNumberAttribution("4444444", "test", Address.UNKNOW,
				new Date()));
		list.add(new MobileNumberAttribution("5555555", "test", Address.UNKNOW,
				new Date()));
		list.add(new MobileNumberAttribution("6666666", "test", Address.UNKNOW,
				new Date()));
		list.add(new MobileNumberAttribution("7777777", "test", Address.UNKNOW,
				new Date()));
		list.add(new MobileNumberAttribution("8888888", "test", Address.UNKNOW,
				new Date()));
		list.add(new MobileNumberAttribution("9999999", "test", Address.UNKNOW,
				new Date()));

		return list;
	}

	@Autowired
	private IMobileNumAttributionService mobileNumAttributionService;

	@Autowired
	private IAddressService addressService;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		methodInvokeLog("doGet(request=" + request + ",response=" + response
				+ ")");

		Operation op = getRequestOperation(request);
		doOperation(op, request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) {
		methodInvokeLog("doPost(request=" + request + ",response=" + response
				+ ")");

		doGet(request, response);
	}

	/**
	 * 解析并返回用户请求的操作类型。如果用户请求的操作类型无法解析，将默认返回Operation.RETRIEVE。
	 * 
	 * @param request
	 *            用户请求
	 * @return 用户请求的操作类型
	 */
	private Operation getRequestOperation(HttpServletRequest request)
			throws IllegalArgumentException {
		methodInvokeLog("getRequestOperation(request=" + request + ")");

		try {
			String operationName = request.getParameter("operation");
			operationName = operationName.toUpperCase();

			return Operation.valueOf(operationName);
		} catch (Exception e) {
			return Operation.RETRIEVE;
		}
	}

	/**
	 * 根据用户请求的操作类型分发后台操作。
	 * 
	 * @param op
	 *            用户请求的操作类型
	 * @param request
	 *            用户请求
	 * @param response
	 *            用户响应
	 */
	private void doOperation(Operation op, HttpServletRequest request,
			HttpServletResponse response) {
		methodInvokeLog("doOperation(request=" + request + ",response="
				+ response + ")");

		switch (op) {
		case CREATE:
			doCreate(request);
			break;
		case UPDATE:
			doUpdate(request);
			break;
		case DELETE:
			doDelete(request);
			break;
		case RETRIEVE:
		default:
			doRetrieve(request);
			jumpToMobileMainPage(request, response);
			break;
		}
	}

	/**
	 * 处理创建操作。
	 * 
	 * @param request
	 *            用户请求
	 */
	private void doCreate(HttpServletRequest request) {
		methodInvokeLog("doCreate(request=" + request + ")");

		mobileNumAttributionService
				.addAttribution(getMobileNumberAttribution(request));
	}

	/**
	 * 处理查询操作。
	 * 
	 * @param request
	 *            用户请求
	 */
	private void doRetrieve(HttpServletRequest request) {
		methodInvokeLog("doRetrieve(request=" + request + ")");

		// List<MobileNumberAttribution> list =
		// mobileNumAttributionService.listAll();

		request.setAttribute(
				"pagination",
				new Pagination<MobileNumberAttribution>(list, 0, 5, 1, (list
						.size() + 9) / 10));
	}

	/**
	 * 处理更新操作。
	 * 
	 * @param request
	 *            用户请求
	 */
	private void doUpdate(HttpServletRequest request) {
		methodInvokeLog("doUpdate(request=" + request + ")");

		mobileNumAttributionService
				.updateAttribution(getMobileNumberAttribution(request));
	}

	/**
	 * 处理删除操作。
	 * 
	 * @param request
	 *            用户请求
	 */
	private void doDelete(HttpServletRequest request) {
		methodInvokeLog("doDelete(request=" + request + ")");

		String mobileNumberSegment = request
				.getParameter("mobileNumberSegment");

		log.debug("Delete with mobileNumberSegment: " + mobileNumberSegment);

		list.remove(new MobileNumberAttribution(mobileNumberSegment, "test",
				Address.UNKNOW, new Date()));
		
		if(list.isEmpty()) {
			list = createList();
		}

		// mobileNumAttributionService
		// .delAttribution(getMobileNumberAttribution(request));
	}

	/**
	 * 从用户请求参数中解析获取MobileNumberAttribution对象。
	 * 
	 * @param request
	 *            用户请求
	 * @return MobileNumberAttribution对象
	 */
	private MobileNumberAttribution getMobileNumberAttribution(
			HttpServletRequest request) {
		methodInvokeLog("getMobileNumberAttribution(request=" + request + ")");

		String mobileNumber = request.getParameter("mobileNumber");
		String mobileNumberSegment = null;
		if (null != mobileNumber) {
			mobileNumberSegment = mobileNumber.substring(0, 7);
		}
		String phoneCardType = request.getParameter("phoneCardType");
		Address address = getAddress(request);

		return new MobileNumberAttribution(mobileNumberSegment, phoneCardType,
				address, new Date());
	}

	/**
	 * 从用户请求参数中解析获取Address对象。
	 * 
	 * @param request
	 *            用户请求
	 * @return Address对象
	 */
	private Address getAddress(HttpServletRequest request) {
		methodInvokeLog("getAddress(request=" + request + ")");

		String areaCode = request.getParameter("areaCode");

		return addressService.loadsByPattern(areaCode, LoadPattern.AREACODE)
				.get(0);
	}

	/**
	 * 跳转到号码管理首页。
	 * 
	 * @param request
	 * @param response
	 */
	private void jumpToMobileMainPage(HttpServletRequest request,
			HttpServletResponse response) {
		methodInvokeLog("jumpToMobileMainPage(request=" + request
				+ ",response=" + response + ")");

		try {
			request.getRequestDispatcher("/mobile/mobileMain.jsp").forward(
					request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 方法调用日志。
	 * 
	 * @param methodDesc
	 *            方法描述
	 */
	private void methodInvokeLog(String methodDesc) {
		LoggerUtil.methodInvokeLog(log, getClass(), methodDesc);
	}

}
